<template>
  <div :class="prefixCls">
    <div
      :class="{[prefixCls + '-highlight']: index % 2 !==0}"
      v-for="(item,index) in textData"
      :key="index"
    >{{item}}
    </div>
  </div>
</template>

<script>
const prefixCls = 'haloe-auto-complete-highlight-box';

export default {
  name: 'HighlightKeyword',
  props: {
    highlight: {
      type: Boolean,
      default: false,
    },
    ignoreCase: {
      type: Boolean,
      default: true,
    },
    keyword: {
      type: [String, Number],
    },
    text: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      prefixCls,
      textData: [],
    }
  },
  mounted() {
    this.setHighlightKeyword()
  },
  methods: {
    setHighlightKeyword() {
      if (!this.keyword || !this.text || !this.highlight || this.disabled) {
        this.textData = [this.text]
        return
      }
      const keyword = String(this.keyword).replace(/([\/\$\^\*\|\(\)\+\?\{\}\[\]\.\\])/g, '\\$1')
      const reg = new RegExp(`(${keyword})`, this.ignoreCase ? 'igm' : 'gm')
      const content = String(this.text)

      let result = {};
      let currentIndex = 0, returnData = [];

      while ((result = reg.exec(content))) {
        returnData.push(content.slice(currentIndex, result.index));
        returnData.push(result[1]);
        currentIndex = result.index + result[0].length;
      }
      if (content.length > currentIndex) {
        returnData.push(content.slice(currentIndex, content.length));
      }
      this.textData = returnData;
    }
  },
  watch: {
    keyword(val) {
      this.setHighlightKeyword()
    },
    text(val) {
      this.setHighlightKeyword()
    }
  }
}
</script>

